#include "stdafx.h"
#include "FileSystemFactory.h"
#include "LocalFileSystem.h"
#include "RemoteFileSystem.h"
#include <mutex>

MAKE_SINGLETON(SyncClient::FileSystemFactory, nullptr)

namespace SyncClient
{
	class FileSystemFactory::Impl
	{
	public:
		Impl()
		{

		}

		~Impl()
		{
			if (localFileSystem_)
			{
				delete localFileSystem_;
				localFileSystem_ = nullptr;
			}
			if (remoteFileSystem_)
			{
				delete remoteFileSystem_;
				remoteFileSystem_ = nullptr;
			}
		}

		IFileSystem * getFileSystem(const FILESYSTEMTYPE type)
		{
			std::lock_guard<std::mutex> lock(mutex_);
			if (type == FILESYSTEMTYPE_LOCAL)
			{
				if (nullptr == localFileSystem_)
				{
					localFileSystem_ = new (std::nothrow)LocalFileSystem;
				}
				return localFileSystem_;
			}
			else if (type == FILESYSTEMTYPE_REMOTE)
			{
				if (nullptr == remoteFileSystem_)
				{
					// wait to implement
					//remoteFileSystem_ = new (std::nothrow)RemoteFileSystem;
				}
				return remoteFileSystem_;
			}
			
			return nullptr;
		}

	private:
		std::mutex mutex_;
		LocalFileSystem* localFileSystem_;
		RemoteFileSystem* remoteFileSystem_;
	};

	FileSystemFactory::FileSystemFactory()
		:impl_(new (std::nothrow) Impl)
	{
	}

	FileSystemFactory::~FileSystemFactory()
	{
	}

	IFileSystem * FileSystemFactory::getFileSystem(const FILESYSTEMTYPE type)
	{
		if (!impl_)
		{
			return nullptr;
		}
		return impl_->getFileSystem(type);
	}
}
